# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,HttpResponse,render_to_response
import json,urllib2,urllib
from crondb.models import CrontabsInfo
import datetime,re
# Create your views here.

def Index(request):
   return render_to_response('index.html')


def ReadMe(request):
    return render_to_response('readme.html')

def DbPage(request):
    Response = CrontabsInfo.objects.order_by('id')

    return render_to_response('dbpage.html', {'Response':Response})


def ManagePage(request):
    Hosts = CrontabsInfo.objects.all()
    dict = {}
    for Host in Hosts:
        dict[Host.IpAddress] = [ Host.HostName, Host.UpdateTime, Host.Status ]
    return render_to_response('managecron.html',{'data': dict})


def HostList(request):
    dict = {

    }
    GetDb = CrontabsInfo.objects.all()
    print  GetDb
    for i in GetDb:
        print i

def GetAgent(request):
    if request.method == "POST":
        print request.META
        RemoteAddr = request.META['REMOTE_ADDR']
        PostData = request.POST["json"]
        DictPostData = eval(PostData)
        print ">>>>>> DictPostData['Crontab'] is :",DictPostData['Crontabs']
        check = CrontabsInfo.objects.filter(IpAddress=RemoteAddr)
        print ">>>>>> check len is", len(check)
        if len(check) == 0:
            for k,v in DictPostData['Crontabs'].items():
                for kk,vv in v.items():
                    Osdb = CrontabsInfo(
                        User = k,
                        Crontabs_id = kk,
                        IpAddress = RemoteAddr,
                        HostName = DictPostData['HostName'],
                        IsActive = vv['crontab']['IsActive'],
                        Minute = vv['crontab']['Minute'],
                        Hour = vv['crontab']['Hour'],
                        Day = vv['crontab']['Day'],
                        Month = vv['crontab']['Month'],
                        Week = vv['crontab']['Week'],
                        Command = vv['crontab']['Command'],
                        UpdateTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        Status = 0
                    )
                    Osdb.save()
        else:
            for k,v in DictPostData['Crontabs'].items():
                for kk,vv in v.items():
                    print ">>>>>> User is :", k
                    print ">>>>>> kk is :", kk
                    CronUpdate = check.filter(Crontabs_id=kk,User=k)
                    CronUpdate.update(HostName = DictPostData['HostName'],
                                      IsActive = vv['crontab']['IsActive'],
                                      Crontabs_id = kk,
                                      Minute = vv['crontab']['Minute'],
                                      Hour = vv['crontab']['Hour'],
                                      Day = vv['crontab']['Day'],
                                      Month = vv['crontab']['Month'],
                                      Week = vv['crontab']['Week'],
                                      Command = vv['crontab']['Command'],
                                      UpdateTime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                      )
        return HttpResponse(request)


def AcceptHost(request):
    if request.method == "POST":
        try:
            Ip = request.POST['IpAddress'].split()[0]
            Statu = CrontabsInfo.objects.get(IpAddress=Ip)
            Statu.Status = 1
            Statu.save()
            resu = "success"
        except :
            resu = "api error"
        return HttpResponse(resu)
    else:
        return HttpResponse("Requets must be post")

def ManageHost(request):
    if request.method == "GET":
        Ip = request.GET['IpAddress'].split()[0]
        Crontabs = CrontabsInfo.objects.get(IpAddress=Ip).Crontabs
        HostName = CrontabsInfo.objects.get(IpAddress=Ip).HostName
        CrontabsDict = eval(Crontabs)
        # data = { }
        print CrontabsDict
        return render_to_response('managehost.html',{'data': CrontabsDict,'ip':Ip,'hostname': HostName})
    else:
        return HttpResponse("request method must be get")



def ChangeCron(request):
    if request.method == "POST":
        print ">>>>>> request method is post"
        print ">>>>>> request data is :", request.POST['ss']
        PostData = request.POST['ss']
        try:

            Db = CrontabsInfo.objects.get(IpAddress=request.POST['ss']['IpAddress']).Crontabs
            DictDb = eval(Db)
            DictDb[PostData['user']]['Minute'] = PostData['minute']
            DictDb[PostData['user']]['Hour'] = PostData['hour']
            DictDb[PostData['user']]['Day'] = PostData['day']
            DictDb[PostData['user']]['Month'] = PostData['month']
            DictDb[PostData['user']]['Week'] = PostData['week']
            DictDb[PostData['user']]['Command'] = PostData['command']

            result = "success"
        except:
            result = "api error"
        return HttpResponse(result)
    else:
        return HttpResponse("request method must be post")
